package top.as.sean.api.config;

import cn.dev33.satoken.exception.SaTokenException;
import jodd.net.HttpStatus;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.as.sean.common.exception.GlobalException;
import top.as.sean.common.response.RespStatus;
import top.as.sean.common.response.Result;

import javax.servlet.http.HttpServletResponse;

/**
 * 统一异常处理
 *
 * @author: ArchieSean
 * @date: 2022-09-07 15:37
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 业务异常 可以 抛出给前端
     *
     * @param ex 捕获的异常信息
     * @return 响应数据
     */
    @ExceptionHandler(GlobalException.class)
    public Result<Object> globalExceptionHandler(HttpServletResponse response, GlobalException ex) {
        log.error("[业务异常]：------->{}", ex.getMessage(), ex);
        response.setStatus(HttpStatus.ok().status());
        return Result.fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 系统异常 ，错误信息不能抛给前台， 做日志输出，抛出统一异常信息 fail
     *
     * @param ex 捕获的异常信息
     * @return 响应数据
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> otherExceptionHandler(HttpServletResponse response, Exception ex) {
        log.error("[系统异常]：------->{}", ex.getMessage(), ex);
        response.setStatus(HttpStatus.ok().status());
        return Result.fail(RespStatus.FAIL);
    }

    /**
     * sa-token异常
     *
     * @param response 响应
     * @param ex       捕获的异常信息
     * @return 响应数据
     */
    @ExceptionHandler(SaTokenException.class)
    public Result<Object> saTokenHandler(HttpServletResponse response, SaTokenException ex) {
        log.error("[权限异常]：------->{}", ex.getMessage(), ex);
        response.setStatus(HttpStatus.ok().status());
        String message = ex.getLocalizedMessage();
        String mess = message.contains("：") ? message.substring(0,message.indexOf("：")) : message;
        return Result.fail(mess);
    }

    /**
     * 系统异常 ，错误信息不能抛给前台， 做日志输出，抛出统一异常信息 fail
     *
     * @param ex 捕获的异常信息
     * @return 响应数据
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Object> runtimeExceptionHandler(HttpServletResponse response, RuntimeException ex) {
        log.error("[运行时异常]：------->{}", ex.getMessage(), ex);
        response.setStatus(HttpStatus.ok().status());
        return Result.fail(RespStatus.FAIL);
    }

}
